import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 5000
})

api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器，处理token过期
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export const studentApi = {
  // 获取学生列表
  getList(params = {}) {
    return api.get('/student', { params })
  },

  // 根据ID获取学生详情
  getById(id) {
    return api.get(`/student/${id}`)
  },

  // 创建学生
  create(data) {
    return api.post('/student', data)
  },

  // 更新学生
  update(id, data) {
    return api.put(`/student/${id}`, data)
  },

  // 删除学生
  delete(id) {
    return api.delete(`/student/${id}`)
  }
}

export default api
